import dayjs from 'dayjs';
import canvg from 'canvg';
import UUID from 'uuid';
import { notification } from 'antd';

/**
 * 模拟switch方式筛选值
 * 
 * @param {*} val 目标值
 * @param {arr} keys 键
 * @param {arr} values 值
 * @param {str} invalids 无效值
 */
export function switcher(val, keys = [], values = [], invalids = "void") {
  let res = invalids;
  keys.forEach((key, i) => val === key && (res = values[i]));
  return res;
}

/**
 * 动态引入自定义css文件
 * 
 * @param {*} url css url
 */
export function createCssDom(url) {
  let cssdom = document.createElement('link');
  cssdom.rel = 'stylesheet';
  cssdom.href = url;
  document.head.appendChild(cssdom);
}

/**
 * 动态引入自定义js文件
 * 
 * @param {*} url js url
 */
export function createScriptDom(url) {
  const scriptDom = document.createElement('script');
  scriptDom.type = 'text/javascript';
  scriptDom.async = true;
  scriptDom.src = url;

  return new Promise((resolve) => {
    scriptDom.onload = function () { resolve(); }
    document.body.appendChild(scriptDom);
  });
}

/**
 * 产生期别
 * 
 * @param {number} yearFrom 开始年份 
 * @param {number} yearTo 结束年份
 * @param {boolean} needYear 是否需要年报
 */
export function genPeriods(yearFrom = 2018, 
  yearTo = new Date().getFullYear(), 
  needYear=false, 
  needSeason = true, 
  needMonth = true) {
  if (yearFrom > yearTo) return [];

  const genSeasons = function() {
    let seasons = ["一", "二", "三", "四"];
    return {
      value: "季度",
      label: "季报",
      children: seasons.map((s, i) => {
        return { value: i + 1, label: `第${s}季度` };
      })
    };
  }

  const genMonths = function() {
    let months = [];
    months.length = 12;
    months.fill(1);
    return {
      value: "月",
      label: "月报",
      children: months.map((_, i) => {
        return { value: i + 1, label: `${i + 1}月` };
      })
    };
  }

  let options = [];
  for(let year=yearFrom; year <= yearTo; ++year) {
    let e = {
      value: year,
      label: `${year}年`,
      children: []
    }
    needMonth && e.children.push(genMonths());
    needSeason && e.children.push(genSeasons());
    needYear && e.children.push({
      value: "年",
      label: "年报"
    });
    options.push(e);
  }
  return options;
}

/**
 * 弹出提示消息
 * 
 * @author dsy 2019-03-23
 * @param {*} type 提示类型(error|success)
 * @param {*} title 标题
 * @param {*} content 内容
 */
export function openNotificationWithIcon(type, title, content) {
  notification[type]({
      message: title,
      description: content,
  });
};

/**
 * 转换时间列表中的datetime字段
 *
 * @author dsy 2019-03-02
 * @param {*} timeList 时间列表（包含datetime的字符串转换）
 */
export function dataSwitch(timeList) {
  if (!Array.isArray(timeList)) return [];
  timeList.forEach(x => {
    let datetime = dayjs(new Date(parseInt(x.datetime)));
    x.time = datetime.format('YYYY年MM月DD日');
  });
  return timeList;
}

/**
 * 转换svg格式
 *
 * @author dsy 2019-03-07
 * @param {*} svg <svg>...<svg>
 * @param {*} mode "image/bmp" 或者 "image/jpeg" 或 "image/png"
 */
export function switchSvg(svg, mode) {
  let cvs = document.createElement('canvas');
  canvg(cvs, svg);
  return cvs.toDataURL(mode);
}

/**
 * 下载数据
 *
 * @author dsy 2019-03-07
 * @param {*} url 下载地址
 */
export function download(url) {
  var oA = document.createElement('a');
  oA.download = ''; // 设置下载的文件名，默认是'下载'
  oA.href = url;
  document.body.appendChild(oA);
  oA.click();
  oA.remove(); // 下载之后把创建的元素删除
}

/**
 * 下载Excel文件
 *
 * @author dsy 2019-03-12
 * @param {*} res 返回的excel文件二进制流
 */
export function downloadExcel(res) {
  var blob = new Blob([res], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
  }); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  var downloadElement = document.createElement('a');
  var href = window.URL.createObjectURL(blob); // 创建下载的链接
  downloadElement.href = href;
  downloadElement.download = UUID.v1() + '.xls'; // 下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href); // 释放掉blob对象
}

/**
 * 下载Zip文件
 *
 * @author dsy 2019-03-12
 * @param {*} res 返回的zip文件二进制流
 */
export function downloadZip(res) {
  var blob = new Blob([res], { type: 'application/octet-stream'});
  var downloadElement = document.createElement('a');
  var href = window.URL.createObjectURL(blob); // 创建下载的链接
  downloadElement.href = href;
  downloadElement.download = UUID.v1() + '.zip'; // 下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href); // 释放掉blob对象
}

/**
 * 单表查询条件生成器
 */
export class QueryCond {
  constructor() {
    this.conds = [];
  }

  make(key, value, mode) {
    if (key && value) {
      this.conds.push({
        name: key,
        value: value,
        mode: mode,
      });
    } else {
      throw new Error("name and key can't be void.");
    }
  }

  exactQuery(key, value) {
    this.make(key, value, 0);
  }

  fuzzyRight(key, value) {
    this.make(key, value, 1);
  }

  fuzzyLeft(key, value) {
    this.make(key, value, 2);
  }

  fuzzyQuery(key, value) {
    this.make(key, value, 3);
  }

  getConds() {
    return this.conds;
  }
}

/**
 * 字符串转HTML
 * @param {str} str
 */
export function swichToHTML(str, id, style) {
  style = style? style: {};
  id = id? id: UUID.v4();
  return <div style={style} id={id} dangerouslySetInnerHTML={{ __html: str }} />;
}

/**
 * 获取对象中的某个序号的值
 * 
 * @param {*} obj 对象
 * @param {*} i 序号
 */
export function getValFromObj(obj, i) {
  let count = 0;
  for (let e in obj) {
    if (i == count) return obj[e];
    count++;
  }
  return null;
}

/**
 * 获取对象中的某个序号的kv值
 * 
 * @param {*} obj 对象
 * @param {*} i 序号
 */
export function getObjFromObj(obj, i) {
  let count = 0;
  for (let e in obj) {
    if (i == count) return {key: e, value: obj[e]};
    count++;
  }
  return null;
}

/**
 * 打开PDF文件
 *
 * @author LongTeng 2019-03-15
 * @param {*} res 返回的excel文件二进制流
 */
export function openPDF(res) {
  var blob = new Blob([res], {
    type: 'application/pdf',
  }); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  var downloadElement = document.createElement('a');
  var href = window.URL.createObjectURL(blob); // 创建下载的链接
  downloadElement.href = href;
  window.open(downloadElement.href);
}

/**
 * 数组去重方法
 * 
 * @author LongTeng 2019-03-20
 * @param {arr} res 返回去重过后的数组
 */
export function uniq (array) {
  let temp = []; //一个新的临时数组
  for(let i = 0; i < array.length; i++){
      if(temp.indexOf(array[i]) == -1){
          temp.push(array[i]);
      }
  }
  return temp;
}

/**
 * 将英文括号转换为中文括号
 * @author LongTeng 2019-03-20
 * @param {str} srt pattern srt
 */
export function swichParentheses  (srt) {
  var reg = /[\(]/g,reg2 = /[\)]/g;
  return srt.replace(reg,"（").replace(reg2,"）");;
} 

/**
 * 通过获取ID，打印此DOM元素内所有内容
 * @author LongTeng 2019-03-21
 * @param {str} srt pattern str
 */
export function printOut(id) {
  var newWindow;
  //打开一个新的窗口  
  newWindow = window.open();
  // 是新窗口获得焦点  
  newWindow.focus();
  //保存写入内容  
  var newContent = "<html><head><meta charset='utf-8'/><title>打印</title></head><body>"
  newContent += document.getElementById(id).outerHTML;
  newContent += "</body></html>"
  // 将HTML代码写入新窗口中  
  newWindow.document.write(newContent);
  newWindow.print();
  // close layout stream 
  newWindow.document.close();
  //关闭打开的临时窗口
  newWindow.close();
}


/**
 * 删除非法字符
 * @author LongTeng 2019-03-22
 * @param {str} str 
 */
export function deleteInvalidSigns (str) {
  return str.replace(/(\t|\r|\n)/g,"");
}

/**
 * 获取url路径后部“？”后的参数值，通过输入参数名称获得参数值
 * @author LongTeng 2019-03-24
 * @param {str} str 
 */
export function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}